package dao

import (
	"context"
	"gino/app/common"
	"gino/app/model"
	"gorm.io/gorm"
)

var User = userDao{}

type userDao struct{}

func (d *userDao) Create(ctx context.Context, db *gorm.DB, params model.User) (id int64, err error) {

	err = db.WithContext(ctx).Model(&model.User{}).Create(&params).Error
	if nil != err {
		return
	}

	return params.ID, nil
}

func (d *userDao) List(ctx context.Context, db *gorm.DB, params model.UserListReq) (list []model.User, total int64, err error) {

	entities := make([]model.User, 0, params.PageSize)

	db = db.WithContext(ctx).Model(&model.User{})

	err = db.Count(&total).Error
	err = db.Scopes(common.Paginate(&params.PageInfo)).Order("id DESC").Scan(&entities).Error

	return entities, total, err
}

func (d *userDao) GetByUsername(ctx context.Context, db *gorm.DB, username string) (ret model.User, err error) {

	err = db.WithContext(ctx).Model(&model.User{}).Where("username = ?", username).First(&ret).Error
	if nil != err {
		return model.User{}, err
	}

	return ret, nil
}

func (d *userDao) GetCountByUsername(ctx context.Context, db *gorm.DB, username string) (count int64, err error) {

	err = db.WithContext(ctx).Model(&model.User{}).Where("username = ?", username).Count(&count).Error
	if nil != err {
		return 0, err
	}

	return count, nil
}
